package com.monkey.web.context.strategy;

import com.monkey.core.web.response.MonkeyResponseDto;
import org.apache.commons.lang3.StringUtils;

/**
 * Project  : monkey
 * Author   : Wu Tian Qiang
 * Date     : 2016/9/1
 */
public class MessageCtrlReturnValueHandler extends AbstractCtrlReturnValueHandler {
    private static final String success_prefix = "success:";
    private static final String fail_prefix = "fail:";

    @Override
    public boolean support(Object returnValue) {
        if (returnValue instanceof String) {
            String value = (String) returnValue;
            return value.toLowerCase().startsWith(success_prefix) ||
                    value.toLowerCase().startsWith(fail_prefix);
        }
        return false;
    }

    @Override
    public MonkeyResponseDto handle(Object returnValue, String fieldStr) {
        String value = (String) returnValue;
        if (value.toLowerCase().startsWith(success_prefix)) {
            String message = StringUtils.substringAfter(value.toLowerCase(), success_prefix);
            return new MonkeyResponseDto().success(message);
        } else {
            String message = StringUtils.substringAfter(value.toLowerCase(), fail_prefix);
            return new MonkeyResponseDto().fail(message);
        }
    }


}
